const i18n = require('./utils/i18n/index')
const EventEmitter = require('./utils/eventEmitter')

App({
  globalData: {
    userInfo: {},
    token: '',
    baseUrl: 'https://miniapp.gzqxasa.cn/miniapi/',
    cdnUrl: 'https://miniapp.gzqxasa.cn/',
    isLogin: false,
    locale: 'zh_CN',  // 默认中文
    eventBus: null,
    isLoading: true // 默认加载状态为true
  },
  
  onLaunch() {
    // 初始化事件总线
    this.globalData.eventBus = new EventEmitter()
    
    // 检查登录状态
    const token = wx.getStorageSync('token')
    if (token) {
      this.globalData.token = token
      this.globalData.isLogin = true
    }
  },

  onShow(){
    this.loadUserInfo()
  },

  // 登录流程
  login() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: res => {
          wx.request({
            url: this.globalData.baseUrl + 'auth-session',
            method: 'GET',
            data: {
              code: res.code
            },
            success: loginRes => {
              if (loginRes.data.token) {
                this.setToken(loginRes.data.token)
                resolve(loginRes.data)
              } else {
                // 需要获取手机号登录
                wx.showModal({
                  title: '提示',
                  content: '需要授权手机号完成登录',
                  success: modalRes => {
                    if (modalRes.confirm) {
                      resolve({needPhone: true, openid: loginRes.data.openid})
                    } else {
                      reject(new Error('用户拒绝授权'))
                    }
                  }
                })
              }
            },
            fail: err => {
              reject(err)
            }
          })
        },
        fail: err => {
          reject(err)
        }
      })
    })
  },

    // 加载用户信息
    loadUserInfo() {
        if (!this.globalData.token) {
            return 
        }
        wx.request({
          url: this.globalData.baseUrl + 'api/user-info',
          header: {
            'Authorization': `Bearer ${this.globalData.token}`
          },
          success: res => {
            if (res.statusCode == 401) {
                this.onLogout()
            }
            if (res.data.code === 0) {
               this.globalData.userInfo = res.data.data.user
            }
          }
        })
    },
    onLogout() {
        wx.removeStorageSync('token')
        this.globalData.token = ''
        this.globalData.isLogin = false
      },
  // 手机号登录
  phoneLogin(openid, iv, encryptedData) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: this.globalData.baseUrl + 'phone-login',
        method: 'POST',
        data: {
          openid,
          iv,
          phone_data: encryptedData
        },
        success: res => {
          if (res.data.token) {
            this.setToken(res.data.token)
            resolve(res.data)
          } else {
            reject(new Error('登录失败'))
          }
        },
        fail: err => {
          reject(err)
        }
      })
    })
  },

  // 设置token
  setToken(token) {
    this.globalData.token = token
    this.globalData.isLogin = true
    wx.setStorageSync('token', token)
  },

  // 切换语言
  switchLanguage() {
    const currentLocale = i18n.getLocale()
    const newLocale = currentLocale === 'zh_CN' ? 'en_US' : 'zh_CN'
    i18n.setLocale(newLocale)
  }
}) 